<?php

class UrlToController
{

    public $controller_404 = 'pagenotfound', $controller_index = 'index';
    private $base_path;

    public function __construct() {
        BaseMvc::$listernerHandler->broadCastEventOf('basemvc_UrlToController_init', $this);
    }

    public function findController($base_path) {
        $this->base_path = $base_path;
        BaseMvc::includeLib('Controller', 'basemvc');
        $keys = array_keys($_GET);
        if (!empty($keys[0])) {
            $request = explode('/', trim($keys[0], '/'));
            if (empty($request[0])) {
                $this->useController($this->controller_index);
            } else {
                $controllerName = $request[0];
                $action = 'indexAction';
                $vars = null;
                if (!empty($request[1])) {
                    $action = $request[1] . 'Action';
                    if (isset($request[2])) {
                        $vars = array_slice($request, 2);
                    }
                }
                $this->useController($controllerName, $action, $vars);
            }
        } else {
            $this->useController($this->controller_index);
        }
    }

    private function useController($name, $action = 'indexAction', $vars = null) {
        $path = $this->base_path . $name . '.php';
        if (file_exists($path)) {
            include_once $path;
            if (class_exists($name)) {
                $controller = new $name();
                if (method_exists($controller, $action)) {
                    BaseMvc::$listernerHandler->broadCastEventOf('basemvc_controller_chosen', array('controller' => $controller, 'name' => $name, 'action' => $action));
                    $controller->$action($vars);
                    return;
                }
            }
        }

        $this->controllerNotFound();
    }

    private function controllerNotFound() {
        include_once $this->base_path . $this->controller_404 . '.php';
        $controller = new $this->controller_404();
        BaseMvc::$listernerHandler->broadCastEventOf('basemvc_controller_chosen', array('controller' => $controller, 'name' => $this->controller_404, 'indexAction'));
        $controller->indexAction();
    }

}